package com.wulin;

import com.wulin.mapper.EnvironmentDataMapper;
import com.wulin.mapper.HarvestDataMapper;
import com.wulin.mapper.PestDiseaseDataMapper;
import com.wulin.mapper.UserDataMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.InputStream;

import java.util.List;


import javax.swing.JTable;
import javax.swing.JLabel;
import java.awt.Font;



public class contents_System extends JFrame {
	String resource = "mybatis-config.xml";
	InputStream inputStream = Resources.getResourceAsStream(resource);
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

	SqlSession sqlSession =sqlSessionFactory.openSession();


	private JPanel contentPane;

	private JTable table;
	private String userName;
	private static String userType;
	
	public static void main(String[] args) {
	    EventQueue.invokeLater(() -> {
	        try {
	            // 设置默认用户类型
	        	String userName = "a";
//	        	String user_type = "农业专家";
//	            String user_type = "管理员";
              String user_type = "普通农户";
	            contents_System frame = new contents_System(userName, user_type);
	            frame.setVisible(true);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    });
	}

	/**
	 * Create the frame.
	 */
	public contents_System(String userName, String userType) throws IOException {
		this.userName = userName;
		this.userType = userType;

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 1414, 813);

		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("欢迎，"+userName);
		lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 30));
		lblNewLabel.setBounds(984, 11, 339, 40);
		contentPane.add(lblNewLabel);
		
		JButton btnNewButton = new JButton("查询");
		
		btnNewButton.setBounds(475, 11, 144, 40);
		contentPane.add(btnNewButton);
		
		JComboBox comboBox = new JComboBox();
		comboBox.setFont(new Font("宋体", Font.PLAIN, 26));
		comboBox.setModel(new DefaultComboBoxModel(new String[] {"environment_data", "harvest_data", "pest_monitor", "user_data", "socket"}));
		comboBox.setBounds(93, 11, 304, 40);
		contentPane.add(comboBox);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(31, 70, 1346, 656);
		contentPane.add(scrollPane);
		
		table = new JTable();
		
		table.setFont(new Font("宋体", Font.PLAIN, 30));
		table.setRowHeight(40);
		scrollPane.setViewportView(table);
		
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String tableName = comboBox.getSelectedItem().toString();
				if(tableName.equals("socket") && (userType.equals("管理员") ||userType.equals("农业专家"))){
                    try {
                        Server frame = new Server();
						frame.setVisible(true);
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }
				else if(tableName.equals("socket")){
                    try {
                        Client frame = new Client();
						frame.setVisible(true);
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }

				try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
					// 动态获取对应的 Mapper 接口
					Object mapper = null;
					if (tableName.equals("environment_data")) {
						mapper = sqlSession.getMapper(EnvironmentDataMapper.class);
					} else if (tableName.equals("harvest_data")) {
						mapper = sqlSession.getMapper(HarvestDataMapper.class);
					} else if (tableName.equals("pest_monitor")) {
						mapper = sqlSession.getMapper(PestDiseaseDataMapper.class);
					} else if (tableName.equals("user_data")) {
						mapper = sqlSession.getMapper(UserDataMapper.class);
					}

					// 调用 Mapper 的 selectAll 方法
					List<?> dataList = (List<?>) mapper.getClass().getMethod("selectAll").invoke(mapper);

					// 动态生成表头
					DefaultTableModel model = new DefaultTableModel();
					if (dataList.isEmpty()) {
						table.setModel(model);
						return;
					}

					// 获取第一个对象的字段名
					Object firstRow = dataList.get(0);
					java.lang.reflect.Field[] fields = firstRow.getClass().getDeclaredFields();
					for (java.lang.reflect.Field field : fields) {
						model.addColumn(field.getName());
					}

					// 填充数据
					for (Object row : dataList) {
						Object[] rowData = new Object[fields.length];
						for (int i = 0; i < fields.length; i++) {
							fields[i].setAccessible(true);
							rowData[i] = fields[i].get(row);
						}
						model.addRow(rowData);
					}

					table.setModel(model);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
//              String sql = "SELECT * FROM " + tableName;
//				JbdcObdcConnection db = new JbdcObdcConnection();
//				ResultSet rs = db.executeQuery(sql);
//				DefaultTableModel model = new DefaultTableModel();
//				try{
//					ResultSetMetaData metaData = rs.getMetaData();
//					int columnCount = metaData.getColumnCount();
//					for(int i = 1; i <= columnCount; i++){
//						Vector<String> column = new Vector<>();
//						column.add(metaData.getColumnName(i));
//						model.addColumn(column);
//					}
//					while (rs.next()) {
//		                Object[] rowData = new Object[columnCount];
//		                for (int i = 1; i <= columnCount; i++) {
//		                    rowData[i - 1] = rs.getObject(i);
//		                }
//		                model.addRow(rowData);
//		            }
//				}catch (SQLException ex) {
//		            ex.printStackTrace();
//		        table.setModel(model);
			}
		});
		
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				 try {
					 int selectedRow = table.getSelectedRow();
						
					 String tableName = comboBox.getSelectedItem().toString();
					 if(tableName.equals("environment_data")){
						 if (selectedRow == -1) {
							 JOptionPane.showMessageDialog(contents_System.this, "请选择一行数据", "错误", JOptionPane.ERROR_MESSAGE);
							 return;
						 }
						 String id=table.getValueAt(selectedRow, 0).toString();
						 String cnte=table.getValueAt(selectedRow, 1).toString();//记录时间
						 String tem=table.getValueAt(selectedRow, 2).toString();//环境温度
						 String hum=table.getValueAt(selectedRow, 3).toString();//湿度
						 String light=table.getValueAt(selectedRow, 4).toString();//光照强度
						 String slme=table.getValueAt(selectedRow, 5).toString();//土壤湿度
						 String slfy=table.getValueAt(selectedRow, 6).toString();//土壤肥力
						 details_one frame = new details_one();
						 frame.setVisible(true);
							
						 frame.textField.setText(id);
						 frame.textField_1.setText(cnte);
						 frame.textField_3.setText(tem);
						 frame.textField_6.setText(hum);
						 frame.textField_5.setText(light);
						 frame.textField_4.setText(slme);
						 frame.textField_7.setText(slfy);
					 }
					 else if(tableName == "harvest_data"){
						 if (selectedRow == -1) {
							 JOptionPane.showMessageDialog(contents_System.this, "请选择一行数据", "错误", JOptionPane.ERROR_MESSAGE);
							 return;
						 }
						 String id=table.getValueAt(selectedRow, 0).toString();
						 String apty=table.getValueAt(selectedRow, 1).toString();//农产品
						 String pgaa=table.getValueAt(selectedRow, 2).toString();//种植面积
						 String yield=table.getValueAt(selectedRow, 3).toString();//产量
						 String htte=table.getValueAt(selectedRow, 4).toString();//收获时间
						 String ptaa=table.getValueAt(selectedRow, 5).toString();//种植地区
						 details_two frame = new details_two();
						 frame.setVisible(true);
							
						 frame.textField.setText(id);
						 frame.textField_1.setText(apty);
						 frame.textField_3.setText(pgaa);
						 frame.textField_6.setText(yield);
						 frame.textField_5.setText(htte);
						 frame.textField_4.setText(ptaa);
					 }else if(tableName == "pest_monitor"){
						 if (selectedRow == -1) {
							 JOptionPane.showMessageDialog(contents_System.this, "请选择一行数据", "错误", JOptionPane.ERROR_MESSAGE);
							 return;
						 }
						 String id=table.getValueAt(selectedRow, 0).toString();
						 String mgte=table.getValueAt(selectedRow, 1).toString();//病害时间
						 String cpvy=table.getValueAt(selectedRow, 2).toString();//监测品种
						 String ptte=table.getValueAt(selectedRow, 3).toString();//病害品种
						 String oell=table.getValueAt(selectedRow, 4).toString();//发生程度
						 String dnre=table.getValueAt(selectedRow, 5).toString();//种植地区
						 details_three frame = new details_three();
						 frame.setVisible(true);
							
						 frame.textField.setText(id);
						 frame.textField_1.setText(mgte);
						 frame.textField_3.setText(cpvy);
						 frame.textField_6.setText(ptte);
						 frame.textField_5.setText(oell);
						 frame.textField_4.setText(dnre);
					 }else if(tableName == "user_data"){
						 
						 String id=table.getValueAt(selectedRow, 0).toString();
						 String name=table.getValueAt(selectedRow, 1).toString();//用户名
						 String pswd=table.getValueAt(selectedRow, 2).toString();//密码
						 String urte=table.getValueAt(selectedRow, 3).toString();//用户类型
						 String ctin=table.getValueAt(selectedRow, 4).toString();//联系方式
						 details_four frame = new details_four();
						 frame.setVisible(true);
							
						 frame.textField.setText(id);
						 frame.textField_1.setText(name);
						 frame.textField_3.setText(pswd);
						 frame.textField_6.setText(urte);
						 frame.textField_5.setText(ctin);
					 }
				}catch (Exception ex) {
					ex.printStackTrace();
					JOptionPane.showMessageDialog(contents_System.this, "操作失败: " + ex.getMessage());
				}
			}
		});
	}	
}
